
#ifndef CHATROOMSERVER_TIMERHEAP_H
#define CHATROOMSERVER_TIMERHEAP_H
   
#include <netinet/in.h>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <atomic>       //c++11里的原子操作
#include <unistd.h>    //STDERR_FILENO等
#include <sys/time.h>

//#include  "Net.h"
#define TIMESLOT    300  //00          //定时时间
class heap_timer;                      //前向声明
// 定时器类
class heap_timer
{
public:
    heap_timer(int delay) 
    {
        //expire = time(nullptr) + delay;
    }
	heap_timer() 
    {
        //expire = time(nullptr) + delay;
    }
	~heap_timer()
	{
	}
    void  Init(int delay)
    {
        expire = time(nullptr) + delay;
    }
public:
    time_t expire;                                                              //定时器生效的绝对时间
    std::function<void(void  *)> callBackFunc;          						//回调函数 
    void  *user_data;                                                        	//用户数据
    int    m_TimerId;
};

 
class TimerHeap 
{
public:
     TimerHeap();
    ~TimerHeap();
public:
	// 添加定时器
	void            AddTimer(heap_timer* timer);
	
    //  删除定时器
    void            DelTimer(heap_timer *timer,bool bDeleleFromActive =true); 

    //获取一个定时器timer;
    heap_timer * GetOneTimer();                   

    //回收一个定时器;
     void           PutOneTimer(heap_timer* timer);   

     //程序退出释放所有定时器;
     void           FreeAllTimer();                                     

     //心搏函数检测定时
      void Tick(); 

      //获取头部定时器
    heap_timer* Top();
private:
    bool   m_shutdown;
public:
    bool CreateTimerThread();

    void  Stop();

    static void* TimeOutThread(void* threadData);      					//定时器检测超时线程；			
  					
    std::list<heap_timer*>                     	       m_ActiveTimerList;

    //活动定时器大小
    int                                                              m_nActiveTimer;                         
  
    pthread_mutex_t								       m_ActiveMutexTimer;

    static pthread_cond_t                               m_pthreadCond;       

    bool				                                               m_bStop;


    struct ThreadItemTimout
    {
        pthread_t				    _Handle;                    //线程句柄
        TimerHeap*              _pThis;                         //记录线程池的指针	
        bool							    ifrunning;                       //标记是否正式启动起来，启动起来后，才允许调用StopAll()来释放
        ThreadItemTimout(TimerHeap* pthis) :_pThis(pthis), ifrunning(false) {	}
        ~ThreadItemTimout() {		}
    };
    
    std::vector<ThreadItemTimout*>      	  m_threadVector;      		//线程 容器，容器里就是各个线程了
};

#endif //CHATROOMSERVER_TIMERHEAP_H

